<template>
    <div class="madp-inspection-add">
        <div class="madp-title"></div>
        <div class="madp-form">
            <el-form :model="inspectionForm" :rules="inspectionFormRules" ref="inspectionForm" label-width="100px">
                <el-form-item label="规则名称:" prop="name">
                    <el-input
                        type="text"
                        placeholder="用于企业记录渠道名称或使用场景，名称不会展示给用户"
                        v-model.trim="inspectionForm.name"
                        :onkeyup="(inspectionForm.name = inspectionForm.name.replace(/\s+/g, ''))"
                        maxlength="20"
                        show-word-limit
                    ></el-input>
                </el-form-item>
                <el-form-item label="添加群聊:" prop="groupChat">
                    <div class="madp-form-chat">
                        <div class="madp-form-chat-add">
                            <el-button icon="el-icon-plus" @click="() => openGroupChatDialog()">添加群聊</el-button>
                            <div class="madp-form-chat-add-tips madp-ml">
                                <i class="el-icon-message-solid"></i>
                                <span class="madp-ml">客户群聊内至少有一个员工开通了消息存档功能才可使用哦。</span>
                                <!-- <el-button type="text">
									立即开通消息存档
                                </el-button>-->
                            </div>
                        </div>
                        <div class="madp-form-chat-list" v-if="inspectionForm.groupChat && inspectionForm.groupChat.length > 0">
                            <el-tag v-for="(item, index) in inspectionForm.groupChat" :key="index" closable @close="onDelGroupChat(index)">{{ item.roomName }}</el-tag>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="是否开启:" prop="isOpen">
                    <el-switch v-model="inspectionForm.isOpen" :active-value="1" :inactive-value="2"></el-switch>
                    <span v-if="inspectionForm.isOpen === 1">已开启</span>
                    <span v-if="inspectionForm.isOpen === 2">已关闭</span>
                </el-form-item>
                <el-form-item label="质检时间:" prop="detectionType">
                    <div>
                        <el-radio v-model="inspectionForm.detectionType" :label="1">全天检测</el-radio>
                        <el-radio v-model="inspectionForm.detectionType" :label="2">自定义质检时间</el-radio>
                    </div>
                    <div v-if="inspectionForm.detectionType === 2">
                        <div class="madp-form-time">
                            <el-time-picker
                                v-model="inspectionForm.startTime"
                                placeholder="选择开始时间"
                                :picker-options="{
                                    selectableRange: '00:00:00 - 23:59:59'
                                }"
                                format="HH:mm"
                                value-format="HH:mm"
                            ></el-time-picker>
                            <span class="madp-space-place">至</span>
                            <el-time-picker
                                v-model="inspectionForm.endTime"
                                placeholder="选择结束时间"
                                :picker-options="{
                                    selectableRange: '00:00:00 - 23:59:59'
                                }"
                                format="HH:mm"
                                value-format="HH:mm"
                            ></el-time-picker>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="添加规则:" prop="rulesList">
                    <div class="madp-form-rules">
                        <div v-for="(item, index) in inspectionForm.rulesList" :key="index" class="madp-form-rules-item">
                            <div class="madp-form-rules-item-first">
                                <i class="el-icon-remove-outline" @click="onDelRule(index)"></i>
                                <span class="madp-ml">规则{{ index + 1 }}:为超过</span>
                                <el-input v-model.trim="item.limitTime" @input="item.limitTime = item.limitTime.replace(/[^\d+]/g, '')" class="madp-ml"></el-input>
                                <el-select v-model="item.limitType" placeholder="请选择" class="madp-ml" @focus="closePop">
                                    <el-option :key="1" label="小时" :value="1"></el-option>
                                    <el-option :key="2" label="分钟" :value="2"></el-option>
                                    <!-- <el-option :key="3" label="秒钟" :value="3">
                                    </el-option>-->
                                </el-select>
                                <span class="madp-ml">未回复客户消息的群聊，</span>
                            </div>
                            <div class="madp-form-rules-item-second">
                                <span>给</span>
                                <el-select v-model="item.role" placeholder="请选择" class="madp-role madp-ml" @change="onRoleChange(index)" @focus="closePop">
                                    <el-option v-for="it in roleOptions" :key="it.id" :label="it.name" :value="it.id"></el-option>
                                </el-select>
                                <div class="madp-ml">
                                    <el-popover
                                        placement="bottom"
                                        width="180"
                                        trigger="click"
                                        ref="staffPop"
                                        :disabled="!item.role"
                                        @show="getStaffOptionsByRole(item)"
                                        popper-class="madp-nopad-popover"
                                    >
                                        <div v-show="staffLoading" class="madp-loading">
                                            <i class="el-icon-loading"></i>
                                        </div>
                                        <div v-show="!staffLoading" class="madp-staff">
                                            <div
                                                v-for="it in staffOptions"
                                                :key="it.id"
                                                class="madp-staff-item"
                                                :class="{
                                                    actived: activedStaff === it.id,
                                                    selected: it.id === item.employeeId
                                                }"
                                                @mouseenter="activedStaff = it.id"
                                                @click="onSelectedStaff(it, index)"
                                            >
                                                <div class="madp-staff-item-name">{{ it.name }}</div>
                                            </div>
                                        </div>
                                        <el-input v-model.trim="item.employeeName" :placeholder="item.role ? '请选择' : '请先选择角色'" slot="reference" readonly class="madp-staff-reference">
                                            <div class="madp-staff-reference-suffix" slot="suffix" @mouseenter="item.iconType = 'close'" @mouseleave="item.iconType = 'arrow'">
                                                <i class="el-icon-arrow-down" v-if="item.iconType === 'arrow' || !item.employeeName"></i>
                                                <i class="el-icon-error" v-if="item.iconType === 'close' && item.employeeName" @click.stop="onClearStaff(index)"></i>
                                            </div>
                                        </el-input>
                                    </el-popover>
                                </div>
                                <el-select v-model="item.messageType" placeholder="请选择" class="madp-message madp-ml" @focus="closePop">
                                    <el-option v-for="it in messageOptions" :key="it.id" :label="it.name" :value="it.id"></el-option>
                                </el-select>
                            </div>
                        </div>
                        <div
                            class="madp-form-rules-btn"
                            :class="{
                                'madp-mt': inspectionForm.rulesList && inspectionForm.rulesList.length > 0
                            }"
                        >
                            <div class @click="addOneRule">
                                <i class="el-icon-circle-plus-outline"></i>
                                <el-button type="text" class="madp-ml">添加规则</el-button>
                            </div>
                            <span class="madp-ml">（最多设置8个规则）</span>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button v-if="type == 'update'" type="primary" @click="onSubmit">确认修改</el-button>
                    <el-button v-else type="primary" @click="onSubmit">创建规则</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 选择群聊 开始 -->
        <el-dialog title="添加群聊" :visible.sync="groupChatVisible" :close-on-click-modal="false" top="10vh" custom-class="madp-dialog-add-group" append-to-body width="600px">
            <div class="madp-group-chat-content">
                <div>
                    <el-input placeholder="请输入群名称" v-model.trim="groupChatName">
                        <i slot="suffix" class="el-input__icon el-icon-search"></i>
                    </el-input>
                    <el-button type="primary" @click="handleSearchRoom" class="madp-ml">查询</el-button>
                </div>
                <div class="madp-dialog-add-group-table">
                    <el-scrollbar>
                        <el-table
                            ref="multipleTable"
                            :data="groupChatList"
                            tooltip-effect="dark"
                            @selection-change="handleGroupChatChange"
                            :row-key="getRowKeys"
                            :header-cell-style="{
                                background: 'rgb(255, 191, 191)',
                                color: 'rgb(44,44,44)'
                            }"
                            :stripe="true"
                        >
                            <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
                            <el-table-column prop="groupChat" label="群聊">
                                <template slot-scope="scope">
                                    <div class="madp-content-display">
                                        <img style="width: 52px; height: 52px" src="/img/user.png" alt />
                                        <div class="madp-content-text">
                                            <p>{{ scope.row.roomName }}</p>
                                            <p class="madp-content-desc">
                                                {{ scope.row.currentNum + '/' + scope.row.roomMax }}
                                            </p>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-scrollbar>
                </div>
                <!-- 分页 -->
                <div class="madp-pagination">
                    <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="page.current"
                        :page-sizes="[10, 20, 30, 50, 100]"
                        :page-size="page.size"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="page.total"
                    ></el-pagination>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="groupChatVisible = false">取消</el-button>
                <el-button type="primary" @click="handleGroupChat">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    queryGroupChatList, //群聊列表下拉框
    role, //全部角色查询
    roleMember, //查询所有角色用户
    addInspection, // 新建质检规则
    editInspection //编辑列表
} from '@/api/operation-manage/group-chat-inspection';

export default {
    props: {
        type: String,
        currentRules: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            inspectionForm: {
                name: '',
                groupChat: [],
                detectionType: 1,
                startTime: null,
                endTime: null,
                rulesList: [],
                isOpen: 1
            },
            inspectionFormRules: {
                name: {
                    required: true,
                    message: '请输入规则名称',
                    trigger: 'change'
                },
                groupChat: { required: true, message: '请选择群聊' },
                detectionType: {
                    required: true,
                    message: '请选择质检时间',
                    trigger: 'change'
                },
                rulesList: {
                    required: true,
                    message: '请至少添加一条质检规则',
                    trigger: 'change'
                }
            },
            groupChatVisible: false,
            groupChatList: [],
            groupChatName: '',
            page: {
                current: 1,
                size: 10,
                total: 0
            },
            checkGroupChatList: [],
            getRowKeys(row) {
                return row.roomId;
            },
            roleOptions: [],
            staffOptions: [],
            staffLoading: false,
            activedStaff: '',
            // queryRoleId: '',
            messageOptions: [{ id: 'weiban', name: '发送金融提醒' }, { id: 'phone', name: '拨打电话提醒' }],
            selectItems: [] //选择群聊选中的值
        };
    },
    mounted() {
        console.log('type', this.type, this.currentRules);

        role().then((res) => {
            if (res.data && res.data.code === 0) {
                this.roleOptions = res.data.data;
                this.isUpdate();
                console.log('role', res);
            }
        });
    },
    methods: {
        isUpdate() {
            if (this.type === 'update') {
                // this.currentRules
                const { id, name, groupChat, detectionType, startTime, endTime, rulesList, isOpen } = this.currentRules;
                this.inspectionForm = {
                    id,
                    name,
                    groupChat: this.currentRules.rooms.map((res) => ({
                        currentNum: res.peopleNumber,
                        roomId: res.id,
                        roomMax: res.maxNumber,
                        roomName: res.name
                    })),
                    detectionType,
                    startTime,
                    endTime,
                    rulesList: this.currentRules.rules.map((res) => ({
                        employeeId: [res.sendWho],
                        employeeName: res.names[0], //bug
                        iconType: 'arrow',
                        limitTime: res.time,
                        limitType: res.timeType,
                        messageType: 'weiban',
                        role: 5,
                        id: res.id
                    })),
                    isOpen
                };
            }
        },
        // addSubmit(){
        // 	this.$refs[formName].validate((valid) => {
        // 	if (valid) {

        // 	} else {
        // 		this.$message({
        // 			type: 'warning',
        // 			message: '请填写所有必输项!',
        // 		})
        // 	}
        // 	});
        // },
        //选择群聊 查询
        handleSearchRoom() {
            this.page.current = 1;
            this.openGroupChatDialog();
        },
        /*
         * 选择群聊
         * */
        openGroupChatDialog() {
            let obj = {
                name: this.groupChatName,
                current: this.page.current,
                size: this.page.size
            };
            queryGroupChatList(obj).then((res) => {
                if (res.data.code === 0) {
                    this.groupChatList = res.data.data.data.records || [];
                    this.page.total = res.data.data.data.total;
                    this.$nextTick(() => {
                        if (this.$refs.multipleTable) {
                            this.$refs.multipleTable.clearSelection();
                        }
                        this.groupChatList.forEach((row) => {
                            for (let j in this.inspectionForm.groupChat) {
                                if (row.roomId === this.inspectionForm.groupChat[j].roomId) {
                                    this.$refs.multipleTable.toggleRowSelection(row, true);
                                    break;
                                }
                            }
                        });
                    });
                }
            });
            this.groupChatVisible = true;
        },
        //选择群聊 确定
        handleGroupChat() {
            let selectedGroup = {};
            let selectedGroupId = [];

            this.inspectionForm.groupChat.forEach((item) => {
                selectedGroup[item.roomId] = item;
                selectedGroupId.push(item.roomId);
            });
            if (this.page.current == 1) {
                let newSelected = this.checkGroupChatList.map((item) => {
                    if (selectedGroupId.includes(item.roomId)) {
                        item = selectedGroup[item.roomId];
                    }
                    return item;
                });
                this.inspectionForm.groupChat = [...newSelected];
            } else {
                let newSelected = this.selectItems.map((item) => {
                    if (selectedGroupId.includes(item.roomId)) {
                        item = selectedGroup[item.roomId];
                    }
                    return item;
                });
                this.inspectionForm.groupChat = [...newSelected];
            }
            if (this.inspectionForm.groupChat && this.inspectionForm.groupChat.length > 0) {
                this.$refs.inspectionForm.clearValidate('groupChat');
            }
            this.groupChatVisible = false;
        },
        handleGroupChatChange(data) {
            if (this.page.current == 1) {
                this.checkGroupChatList = data;
                console.log(111, this.checkGroupChatList);
            } else {
                this.selectItems = this.checkGroupChatList.concat(data);
                console.log(222, this.selectItems);
            }
        },
        onDelGroupChat(index) {
            this.inspectionForm.groupChat.splice(index, 1);
        },
        addOneRule() {
            this.inspectionForm.rulesList.push({
                limitTime: '',
                limitType: '',
                role: '',
                messageType: '',
                employeeId: [],
                employeeName: '',
                iconType: 'arrow'
            });
            this.$refs.inspectionForm.clearValidate('rulesList');
        },
        onDelRule(index) {
            this.inspectionForm.rulesList.splice(index, 1);
        },
        onRoleChange(index) {
            if (this.$refs.staffPop && this.$refs.staffPop[index]) {
                this.$refs.staffPop[index].doClose();
                // this.queryRoleId = this.inspectionForm.rulesList[index].role;
                // roleMember({roleId:this.inspectionForm.rulesList[index].role}).then((res)=>{
                // 	if(res.data&&res.data.code === 0){
                // 		this.staffOptions = res.data.data;
                // 		console.log('roleMember',res)
                // 	}
                // })
            }
        },
        getStaffOptionsByRole(records) {
            // if (this.queryRoleId !== records.role) {
            // 	return
            // }
            // this.queryRoleId = records.role
            this.staffLoading = true;
            roleMember({ roleId: records.role })
                .then((res) => {
                    this.staffLoading = false;
                    if (res.data && res.data.code === 0) {
                        this.staffOptions = res.data.data;
                    }
                })
                .catch(() => {
                    this.staffLoading = false;
                });
        },
        onSelectedStaff(records, index) {
            const ind = this.inspectionForm.rulesList[index].employeeId.findIndex((item) => item == records.id);
            if (!(ind > -1)) {
                this.inspectionForm.rulesList[index].employeeId.push(records.id);
                // this.inspectionForm.rulesList[index].roleId.push(
                // 	records.role
                // )
                let newList = this.inspectionForm.rulesList[index].employeeName;
                newList = newList ? newList.split(',') : [];
                newList.push(records.name);
                this.inspectionForm.rulesList[index].employeeName = newList.toString();
            }
            if (this.$refs.staffPop && this.$refs.staffPop[index]) {
                this.$refs.staffPop[index].doClose();
            }
            this.$forceUpdate();
        },
        onClearStaff(index) {
            this.inspectionForm.rulesList[index].employeeId = '';
            this.inspectionForm.rulesList[index].employeeName = '';
            this.$forceUpdate();
        },
        closePop() {
            if (this.$refs.staffPop && this.$refs.staffPop.length > 0) {
                this.$refs.staffPop.forEach((item, index) => {
                    this.$refs.staffPop[index].doClose();
                });
            }
        },
        onSubmit() {
            this.$refs.inspectionForm.validate((validate) => {
                if (validate) {
                    let message = '';
                    this.inspectionForm.rulesList.every((item, index) => {
                        if (message) {
                            return;
                        }
                        if (this.inspectionForm.detectionType === 2 && (!this.inspectionForm.startTime || !this.inspectionForm.endTime)) {
                            message = `质检时间为自定义，请选择时间区间`;
                        } else if (!item.limitTime) {
                            message = `请在第${index + 1}条规则输入时间`;
                        } else if (!item.limitType) {
                            message = `请在第${index + 1}条规则选择时间类型`;
                        } else if (!item.role) {
                            message = `请在第${index + 1}条规则选择提醒角色`;
                        } else if (!item.employeeId) {
                            message = `请在第${index + 1}条规则选择提醒成员`;
                        } else if (!item.messageType) {
                            message = `请在第${index + 1}条规则选择提醒类型`;
                        } else if (item.limitTime < 5 && item.limitType == 2) {
                            message = `请在第${index + 1}条规则选择时间不小于5分钟`;
                        }
                    });
                    if (message) {
                        this.$message.error(message);
                        return;
                    }
                    console.log('this.inspectionForm', this.inspectionForm);

                    const { detectionType, endTime, id, isOpen, name, startTime } = this.inspectionForm;

                    const data = {
                        detectionType,
                        endTime,
                        id,
                        isOpen,
                        name,
                        roomIds: this.inspectionForm.groupChat.map((res) => res.roomId).join(','),
                        rules: this.inspectionForm.rulesList.map((res, index) => ({
                            roleId: res.role,
                            sendWho: res.employeeId[0],
                            time: res.limitTime,
                            timeType: res.limitType,
                            id: res.id || null
                        })),
                        startTime
                    };

                    console.log('data', data);
                    if (this.type === 'update') {
                        editInspection(data).then((res) => {
                            if (res.data && res.data.code == 0) {
                                this.$message({
                                    type: 'success',
                                    message: '修改成功!'
                                });
                                this.$emit('addSuccess');
                                // console.log('addInspection',res)
                            }
                        });
                    } else {
                        addInspection(data).then((res) => {
                            if (res.data && res.data.code == 0) {
                                this.$message({
                                    type: 'success',
                                    message: '添加成功!'
                                });
                                this.$emit('addSuccess');
                            }
                        });
                    }
                }
            });
        },
        // 分页
        handleSizeChange(size) {
            this.page.size = size;
            this.openGroupChatDialog();
        },
        handleCurrentChange(current) {
            this.page.current = current;
            this.openGroupChatDialog();
        }
    }
};
</script>

<style lang="scss" scoped>
.madp-inspection-add {
    .madp-form {
        /deep/ .el-input {
            width: 400px;
        }
        &-chat {
            &-add {
                display: flex;
                &-tips {
                    padding: 0 10px;
                    background-color: #f7fcff;
                    color: #999;
                }
            }
        }
        &-time {
            /deep/ .el-input {
                width: 200px;
            }
            .madp-space-place {
                margin: 0 10px;
            }
        }
        &-rules {
            width: 600px;
            padding: 0 16px;
            background-color: #fbfbfb;
            border: 1px solid #eee;
            &-item {
                padding-top: 16px;
                &-first {
                    /deep/ .el-input {
                        width: 50px;
                    }
                    /deep/ .el-select {
                        .el-input {
                            width: 80px;
                        }
                    }
                }
                &-second {
                    margin-left: 24px;
                    display: flex;
                    .madp-role {
                        /deep/ .el-input {
                            width: 140px;
                        }
                    }
                    .madp-staff {
                        /deep/ .el-input {
                            width: 180px;
                        }
                    }
                    .madp-message {
                        /deep/ .el-input {
                            width: 120px;
                        }
                    }
                }
            }
            &-btn {
                display: flex;
                align-items: center;
            }
        }
    }
}
.madp-ml {
    margin-left: 10px;
}
.madp-mt {
    margin-top: 16px;
}
.el-icon-remove-outline,
.el-icon-circle-plus-outline {
    font-size: 14px;
    cursor: pointer;
}
.madp-dialog-add-group-table {
    margin-top: 10px;
    /deep/ .el-scrollbar {
        height: 50vh;
    }
}
/*选择群聊*/
.madp-group-chat-content {
    .el-input {
        width: 400px;
    }
    .madp-group-chat-wrapper {
        .madp-group-chat-list {
            display: flex;
            margin-top: 10px;
            padding-bottom: 5px;
            border-bottom: 1px solid #dddddd;

            .madp-list-left {
                margin-right: 5px;
                width: 60px;
                height: 60px;
            }

            .madp-list-right {
                flex: 1;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
        }
    }
}
.madp-content-display {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    img {
        max-width: 100px;
    }
    .madp-content-text {
        padding-left: 12px;

        .madp-content-desc {
            font-size: 12px;
            color: #999;
        }
    }
}
.madp-pagination {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
}
.el-tag {
    margin: 2px;
}
.madp-staff {
    margin: 6px 0;
    &-item {
        padding-left: 16px;
        line-height: 34px;
        display: flex;
        justify-content: space-between;
        cursor: pointer;
        &.actived {
            background-color: #effaff;
            color: rgba(0, 0, 0, 0.65);
        }
        &.selected {
            font-weight: bold;
        }
        &-name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
}
.madp-staff-reference {
    width: 180px !important;
    /deep/ input {
        width: 180px;
        cursor: pointer;
    }
    &-suffix {
        cursor: pointer;
    }
}
.madp-loading {
    text-align: center;
}
</style>
